package com.allwees.bs.core.model.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @Author Daniel
 * @Version 1.0.0
 * @Description 打印系统参数
 * @CreateTime 2020/8/14 20:34
 */
@Slf4j
@Configuration
public class ApplicationConfigPrinter implements InitializingBean {

    @Resource
    private ConfigurableEnvironment springEnv;

    @Override
    public void afterPropertiesSet(){
        MutablePropertySources propSrcs = springEnv.getPropertySources();
        Map<String, String> props = StreamSupport.stream(propSrcs.spliterator(), false)
                .filter(ps -> ps instanceof EnumerablePropertySource)
                .map(ps -> ((EnumerablePropertySource<?>) ps))
                .map(EnumerablePropertySource::getPropertyNames)
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toMap(Function.identity(), springEnv::getProperty));

        int interval = 5;
        int maxLength = props.keySet().stream()
                .max(Comparator.comparingInt(String::length))
                .orElse("")
                .length();

        StringBuilder params = new StringBuilder("\n#########################################################################################################################\n");
        props.keySet().stream()
                .sorted()
                .forEach(key -> {
                    int repeatTimes = maxLength - key.length() + interval;
                    String join = StringUtils.repeat(" ", repeatTimes);
                    params.append(key).append(join).append(props.get(key)).append("\n");
                });
        params.append("#########################################################################################################################");
        log.info(params.toString());
    }
}
